/*
*
* Copyright (c) 2011 Vaulting Systems International
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy 
* of this software and associated documentation files (the "Software"), to deal 
* in the Software without restriction, including without limitation the rights 
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 
* of the Software, and to permit persons to whom the Software is furnished to do  
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all  
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE  
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package com.ekeyman.admin.action;

import java.util.StringTokenizer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.core.context.SecurityContextHolder;

import com.ekeyman.admin.security.EkeymanUserDetails;
import com.ekeymanlib.business.KeyManager;
import com.ekeymanlib.domain.User;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;

public class EditAppDeviceAction extends ActionSupport implements Preparable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 5404639506220627320L;
	private static final Log  log = LogFactory.getLog(EditAppDeviceAction.class);
	private KeyManager keyManager;
	private String oper = "edit";
	private String id;
	private String application;
	private String device;
	private String publicKey;
	private String privateKey;
	private String generateNewPrivateKey;
	private String apiKey;

	/*
	 * Extracts the OpenID url from EkeymanUserDetails, then finds 
	 * the user associated with the OpenID url. The apiKey is set
	 * from the vendor associated with the user.
	 */	  
	public void prepare() throws Exception {
		EkeymanUserDetails ekeymanUserDetails = 
			(EkeymanUserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		
		User user = keyManager.getUser(ekeymanUserDetails.getUsername());
		if(user!= null){
			apiKey = user.getVendor().getApiKey();
		}
		
	}

	/*
	 * Determines which edit operation is being requested.
	 * Add is not used as application devices can only be added through the
	 * web service. Edit only allows a new private key to be generated. Del
	 * deletes the application device.
	 */
	public String execute() throws Exception {
		String result = NONE;
		
		try{
			if (oper.equalsIgnoreCase("add")){
				// Not used...App Devices can only be added through web service
			}
			else if (oper.equalsIgnoreCase("edit")) {
				if(generateNewPrivateKey.equalsIgnoreCase("Yes")){
					keyManager.generateNewPrivateKey(publicKey, apiKey);
				}
			}
			else if (oper.equalsIgnoreCase("del")){
		        StringTokenizer ids = new StringTokenizer(id, ",");
		        while (ids.hasMoreTokens())
		        {
		          int removeId = Integer.parseInt(ids.nextToken());
		          keyManager.deleteAppDeviceById(removeId, apiKey);
		        }
			}
		}
		catch(Exception e){
		      addActionError("ERROR : " + e.getLocalizedMessage());
		      result = ERROR;
		}
		return result;
	}

	public void setKeyManager(KeyManager keyManager) {
		this.keyManager = keyManager;
	}

	/*
	 * BE CAREFUL! - When the action is serialized as a JSON object all getters are
	 * executed. While traversing the object graph for keyManager, JSON will encounter
	 * objects (i.e. Hibernate object) that cannot be serialized. The exception will go
	 * undetected as JQGrid has no way to report it!
	 * 
	public KeyManager getKeyManager() {
		return keyManager;
	}
	*/

	public void setOper(String oper) {
		this.oper = oper;
	}

	public String getOper() {
		return oper;
	}
	
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getApplication() {
		return application;
	}

	public void setApplication(String application) {
		this.application = application;
	}

	public String getDevice() {
		return device;
	}

	public void setDevice(String device) {
		this.device = device;
	}

	public void setPublicKey(String publicKey) {
		this.publicKey = publicKey;
	}

	public String getPublicKey() {
		return publicKey;
	}

	public void setPrivateKey(String privateKey) {
		this.privateKey = privateKey;
	}

	public String getPrivateKey() {
		return privateKey;
	}

	public void setGenerateNewPrivateKey(String generateNewPrivateKey) {
		this.generateNewPrivateKey = generateNewPrivateKey;
	}

	public String getGenerateNewPrivateKey() {
		return generateNewPrivateKey;
	}
}
